﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;


namespace GIVisualEditor
{
    public partial class frmMain : Form
    {
        public static string sThisAssemblyFolderPath = "";
        public const int MAX_MRU_ENTRY_LENGTH = 100;
        public const int MAX_MRU_HISTORY_TO_MAINTAIN = 10;

        public frmMain()
        {
            InitializeComponent();
            this.Load += new EventHandler(frmMain_Load);
        }

        void frmMain_Load(object sender, EventArgs e)
        {
            bool gotAnUpgrade = false;


            // We check if there's a better version & upgrade outself
            if (Properties.Settings.Default != null &&
                    Properties.Settings.Default.LastCheckedForUpgrade != null)
            {
                checkForUpdatesToolStripMenuItem.ToolTipText = "Last checked on " + Properties.Settings.Default.LastCheckedForUpgrade.ToShortDateString();
                if (DateTime.Now.Subtract(Properties.Settings.Default.LastCheckedForUpgrade).Days >= 1)
                {
                    gotAnUpgrade = Updater.SelfUpdateManager.CheckAndUpgrade();
                    /* mark that we did make a upgrade request today */
                    Properties.Settings.Default.LastCheckedForUpgrade = DateTime.Now;
                    Properties.Settings.Default.Save();
                }
            }


            if (!gotAnUpgrade)
            {
                // Allow code generation through XSLT transformation
                // This tool will drive through a sligthly different XML schema. We need to change the GIMachine XML schema ... currently the NextState HAS to be as sub-node & cannot be a reference.
                // In many cases we would like to have states separate & resuse them through references

                sThisAssemblyFolderPath = Assembly.GetAssembly(typeof(frmMain)).Location;
                sThisAssemblyFolderPath = sThisAssemblyFolderPath.Substring(0, sThisAssemblyFolderPath.LastIndexOf(@"\") + 1);
                DirectoryInfo oDirectory = new DirectoryInfo(sThisAssemblyFolderPath);
                FileInfo[] allTransformers = oDirectory.GetFiles("*.xslt");
                if (allTransformers != null && allTransformers.Length > 0)
                {
                    foreach (FileInfo F in allTransformers)
                    {

                        generateGIMachineCodeToolStripMenuItem.DropDownItems.Add(F.Name.Substring(0, F.Name.LastIndexOf(".")), null, new EventHandler(CodeGenItemClicked));
                    }

                }
                else
                {
                    generateGIMachineCodeToolStripMenuItem.Enabled = false;
                }

                openToolStripMenuItem_Click(null, null);

                if (Properties.Settings.Default != null && Properties.Settings.Default.IsFirstTimeUsage)
                {
                    FirstTimeUsageGuide oHelper = new FirstTimeUsageGuide();
                    oHelper.Show();
                    oHelper.BringToFront();
                }

                ResetMRUList();

            }
            else
            {
                this.Close();
            }
        }

        private void ResetMRUList()
        {
            if (Properties.Settings.Default != null && Properties.Settings.Default.MRUList != null && Properties.Settings.Default.MRUList.Count > 0)
            {
                recentlyUsedToolStripMenuItem.DropDownItems.Clear();

                for (int i = 0; i < Properties.Settings.Default.MRUList.Count; i++)
                {
                    string sFilePath = Properties.Settings.Default.MRUList[i];
                    if (sFilePath.Length > MAX_MRU_ENTRY_LENGTH)
                    {
                        sFilePath = sFilePath.Substring(sFilePath.Length - MAX_MRU_ENTRY_LENGTH);
                    }

                    recentlyUsedToolStripMenuItem.DropDownItems.Add(sFilePath, null, new EventHandler(OpenFromMRUList));
                    recentlyUsedToolStripMenuItem.DropDownItems[i].Tag = Properties.Settings.Default.MRUList[i]; 

                }
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GIVisualEditor oNew = new GIVisualEditor();
            oNew.MdiParent = this;
            oNew.Show();
            oNew.BringToFront();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Check for IsDirty flag for all MDI childs

            this.Close();
        }

        private void OpenFromMRUList(object sender, EventArgs e)
        {
            if (sender is ToolStripDropDownItem)
            {
                ToolStripDropDownItem oItem = sender as ToolStripDropDownItem;
                if (oItem.Tag != null)
                {
                    string sFilePath = oItem.Tag.ToString();
                    GIVisualEditor oNew = new GIVisualEditor(sFilePath);
                    oNew.MdiParent = this;
                    oNew.Show();
                    oNew.BringToFront();
                }
            }
            

        }

        private void CodeGenItemClicked(object sender, EventArgs e)
        {
            //MessageBox.Show("hola ...coming...");
            if (this.ActiveMdiChild != null && this.ActiveMdiChild is GIVisualEditor)
            {
                ToolStripDropDownItem oMenuItem = sender as ToolStripDropDownItem;
                string what = oMenuItem.Text;
                string xsltPath = string.Format("{0}{1}.xslt", sThisAssemblyFolderPath, what.ToString() );
                saveFileDialog1.Filter = "js file(*.js)|*.js|All files(*.*)|*.*";
                saveFileDialog1.Title = "Select where to save generated code...";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    GIVisualEditor oEditor = this.ActiveMdiChild as GIVisualEditor;
                    oEditor.TransformToCode(xsltPath, saveFileDialog1.FileName);
                }
            }
            else
            {
                MessageBox.Show("No active visual digram found ...");
            }
        }

        private void javaScriptCodeToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null && this.ActiveMdiChild is GIVisualEditor)
            {
                saveFileDialog1.Filter = "xml file(*.xml)|*.xml|All files(*.*)|*.*";
                saveFileDialog1.Title = "Select where to save this grammar...";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    GIVisualEditor oEditor = this.ActiveMdiChild as GIVisualEditor;
                    oEditor.SaveToFile(saveFileDialog1.FileName);

                    if (Properties.Settings.Default.MRUList == null)
                    {
                        Properties.Settings.Default.MRUList = new System.Collections.Specialized.StringCollection();
                    }

                    if (Properties.Settings.Default.MRUList.Count >= MAX_MRU_HISTORY_TO_MAINTAIN)
                    {
                        Properties.Settings.Default.MRUList.RemoveAt(0);
                    }

                    if (!Properties.Settings.Default.MRUList.Contains(saveFileDialog1.FileName)) // Issue: this check is case sensitive ?
                    {
                        Properties.Settings.Default.MRUList.Add(saveFileDialog1.FileName);
                        Properties.Settings.Default.Save();
                        ResetMRUList();
                    }

                }
            }
            else
            {
                MessageBox.Show("No active visual digram found ...");
            }
        }

        private void openToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "xml file(*.xml)|*.xml|All files(*.*)|*.*";
            openFileDialog1.Title = "Open grammar file...";
            openFileDialog1.FileName = "";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                GIVisualEditor oNew = new GIVisualEditor(openFileDialog1.FileName);
                oNew.MdiParent = this;
                oNew.Show();
                oNew.BringToFront();

            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox oAbout = new AboutBox();
            oAbout.ShowDialog();
        }

        private void contentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmHelpContent oHelp = new frmHelpContent();
            oHelp.Show();
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool bUpgrade = Updater.SelfUpdateManager.CheckAndUpgrade();
            if (!bUpgrade)
            {
                MessageBox.Show("No upgrades found.\nThis program has a auto-upgrade detector,\nit'll notify you (checks only once per day) when an upgrade is available.");
            }
        }

        private void generateHTMLTestPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ActiveMdiChild != null && this.ActiveMdiChild is GIVisualEditor)
            {
                saveFileDialog1.Filter = "HTML file(*.htm)|*.htm|All files(*.*)|*.*";
                saveFileDialog1.Title = "Select where to save generated html file...";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    GIVisualEditor oEditor = this.ActiveMdiChild as GIVisualEditor;
                    oEditor.GenerateTestHTML(saveFileDialog1.FileName);
                }
            }
            else
            {
                MessageBox.Show("No active visual digram found ...");
            }
            
        }

        private void importExistingGrammarToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }
    }
}
